package com.ciko.code.http;

import android.content.Context;

import com.ciko.code.constant.Constants;
import com.ciko.code.utils.AppUtils;
import com.ciko.code.utils.NetWorkUtils;
import com.ciko.code.utils.ToastUtils;
import com.ciko.code.utils.Utils;
import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.PersistentCookieStore;
import com.mywork.WorkUIKit;
import com.orhanobut.logger.Logger;

import org.apache.http.client.params.ClientPNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpProtocolParams;

public class HttpClient implements TJHttp {

    private final String TAG = this.getClass().getSimpleName();

    private AsyncHttpClient mHttpClient;

    private PersistentCookieStore mCookieStore;

    private static HttpClient client;

    private Context mContext;

    private HttpClient(Context context) {
        this.mContext = context;
        this.mHttpClient = new AsyncHttpClient();

//        initHttpParam(context);
    }

    /*设置Http参数 此项目无用，使用默认设置*/
    private void initHttpParam(Context context) {
        this.mHttpClient = new AsyncHttpClient(true, Constants.HTTP_TEST_PORT, Constants.HTTPS_PORT);
        this.mCookieStore = new PersistentCookieStore(context);
        this.mHttpClient.setCookieStore(mCookieStore);
        this.mHttpClient.addHeader("Accept-Language", AppUtils.instance(WorkUIKit.getContext()).getLocales());
        this.mHttpClient.getHttpClient().getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
        // 网络状态检测,会处理底层连接不可用的状态
        this.mHttpClient.getHttpClient().getParams().setParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, true);
        this.mHttpClient.setTimeout(10 * 1000);
        this.mHttpClient.setMaxConnections(5);
        this.mHttpClient.setMaxRetriesAndTimeout(3, 1500);
        mHttpClient.setUserAgent(Utils.getUA(mContext));
        DefaultHttpClient defClient = (DefaultHttpClient) mHttpClient.getHttpClient();
        HttpProtocolParams.setUseExpectContinue(defClient.getParams(), false);
    }

    public static HttpClient getInstance(Context context) {
        if (client == null) {
            synchronized (HttpClient.class) {
                client = new HttpClient(context);
            }
        }
        return client;
    }


    /**
     * http post
     */
    @Override
    public void post(final BaseRequest request, final HttpResponseListener listener) {
        sendPostRequest(request, listener);
    }

    /**
     * http get
     */
    @Override
    public void get(final BaseRequest request, final HttpResponseListener listener) {
        sendGetRequest(request, listener);
    }

    private void sendPostRequest(BaseRequest request, HttpResponseListener listener) {

        String tag = request.getClass().getSimpleName();

        Logger.t(tag + "-接口").d(request.getClass().getSimpleName() + "请求接口URL:" + request.getUrl());
        Logger.t(tag + "-参数").json(new Gson().toJson(request.getUrlParam()));

        TJBaseHttpHandler handler = new TJBaseHttpHandler(listener, tag,request.getResponseClazz());

        if (!NetWorkUtils.isConnected(mContext)) {
            handler.onFailure(-1, null, "network is unavailable".getBytes(), null);
            ToastUtils.showShort("网络错误，请检查网络");
        } else {
                if (mHttpClient.post(mContext, request.getUrl(), request, handler) != null) {
                    handler.onSuccess(-1, null, "network is available".getBytes());
                }
        }
    }

    private void sendGetRequest(BaseRequest request, HttpResponseListener listener) {

        String tag = request.getClass().getSimpleName();

        TJBaseHttpHandler handler = new TJBaseHttpHandler(listener, tag, request.getResponseClazz());
        if (!NetWorkUtils.isConnected(mContext)) {
            handler.onFailure(-1, null, "network is unavailable".getBytes(), null);
            ToastUtils.showShort("网络错误，请检查网络");
        } else {

            if (mHttpClient.get(mContext, request.getUrl(), request, handler) != null) {
                handler.onSuccess(-1, null, "network is available".getBytes());
            }


        }
    }

    /**
     * 清除cookie
     */
    public void clearCookie() {
        mCookieStore.clear();
    }

}
